<template>
  <e-charts
    v-if="!isEmpty"
    id="sale-echarts"
    theme="ovilia-green"
    :options="echartsOptions"
    ref="myecharts"
  ></e-charts>
  <div v-else class="empty">暂无数据</div>
</template>

<script>
import ECharts from 'vue-echarts/components/ECharts.vue'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/polar'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/legend'
import 'echarts/lib/chart/line'
export default {
  props: {
    datas: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      isEmpty: false,
      echartsOptions: {
        color: ['#2bcd8e', '#ff6347'],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}人 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: []
        },
        series: [
          {
            name: '性别占比',
            type: 'pie',
            radius: '50%',
            data: [],
            label: {
              show: false
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    }
  },
  components: {
    ECharts
  },
  created () {
    if (this.datas.length) {
      this.handleDatas(this.datas)
    }
  },
  mounted () {
    window.addEventListener('resize', this.loadEcharts)
  },
  methods: {
    handleDatas (data) {
      this.echartsOptions.legend.data = data.map((item) => {
        return item.title
      })
      this.echartsOptions.series[0].data = data.map(item => {
        return { value: item.count || 0, name: item.title }
      })
      this.echartsOptions.formatter = function (name) {
        let result = ''
        for (let i = 0, len = data.length; i < len; i++) {
          if (data[i].title === name) {
            result = name + '  ' + data[i].count + '人  ' + data[i].balance + '%'
          }
        }
        return result
      }
    },
    loadEcharts () {
      if (this.$refs['myecharts']) {
        setTimeout(() => {
          this.$refs['myecharts'].resize()
        }, 10)
      }
    }
  },
  watch: {
    datas (val) {
      if (!val.length) {
        this.isEmpty = true
      } else {
        this.isEmpty = false
        this.handleDatas(val)
      }
    }
  },
  destroyed () {
    window.removeEventListener('resize', this.loadEcharts)
  }
}
</script>

<style lang="scss" scoped>
#sale-echarts {
  width: 100%;
  height: 100%;
  height: 350px;
}
.empty {
  height: 350px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
  color: #09f;
}
</style>
